package com.zxl.app.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.common.constant.bookorder.BookOrderAuditStatusConstant;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.mapper.SysBookOrderMapper;
import com.zxl.common.mapper.SysMemberMapper;
import com.zxl.common.model.bo.order.BookOrderApply;
import com.zxl.common.model.pojo.SysBookOrder;
import com.zxl.common.model.pojo.SysMember;
import com.zxl.common.model.vo.order.BookOrderStatusVo;
import com.zxl.common.model.vo.order.BookOrderVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author zxw
 * @date 2023/4/1
 */
@Service
public class BookOrderService {
    @Resource
    private SysBookOrderMapper sysBookOrderMapper;
    @Resource
    private SysMemberMapper sysMemberMapper;

    @Transactional(rollbackFor = Exception.class)
    public void book(BookOrderApply bookOrderApply) {
        SysBookOrder sysBookOrder = sysBookOrderMapper.selectOne(new QueryWrapper<SysBookOrder>()
                .eq("member_id", bookOrderApply.getMemberId()));
        if (sysBookOrder == null){
            SysBookOrder bookOrder = new SysBookOrder();
            BeanUtil.copyProperties(bookOrderApply,bookOrder);
            sysBookOrderMapper.insert(bookOrder);
        }else if (!BookOrderAuditStatusConstant.AUDIT_STATUS_REJECT.getCode().equals(sysBookOrder.getAuditStatus())){
            throw new BusinessException("订货申请已提交，请等待审核");
        }else {
            BeanUtil.copyProperties(bookOrderApply,sysBookOrder);
            sysBookOrder.setAuditStatus(BookOrderAuditStatusConstant.AUDIT_STATUS_WAIT.getCode());
            sysBookOrderMapper.updateById(sysBookOrder);
        }
        SysMember sysMember = sysMemberMapper.selectOne(new QueryWrapper<SysMember>()
                .eq("id", bookOrderApply.getMemberId()));
        BeanUtil.copyProperties(bookOrderApply,sysMember);
        sysMemberMapper.updateById(sysMember);
    }

    public BookOrderStatusVo getBookStatus(Integer memberId) {
        SysBookOrder bookOrder = sysBookOrderMapper.selectOne(new QueryWrapper<SysBookOrder>()
                .eq("member_id", memberId));
        BookOrderStatusVo bookOrderStatusVo = new BookOrderStatusVo();
        if (bookOrder != null){
            bookOrderStatusVo.setBook(true);
            bookOrderStatusVo.setAuditStatus(bookOrder.getAuditStatus());
        }
        return bookOrderStatusVo;
    }

    public BookOrderVo getBookInfo(Integer memberId) {
        SysBookOrder bookOrder = sysBookOrderMapper.selectOne(new QueryWrapper<SysBookOrder>()
                .eq("member_id", memberId));
        BookOrderVo bookOrderVo = new BookOrderVo();
        BeanUtil.copyProperties(bookOrder,bookOrderVo);
        return bookOrderVo;
    }
}
